package cn.com.duiba.quanyi.open.demo.utils;

import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * httpclient utils
 *
 * @author zzy
 * @create 2023/12/08 10:46
 **/
public class HttpClientUtils {

    private HttpClientUtils() {
    }

    public static String execHttpPostJson(String url, String json) {
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json");
        // 模拟表单
        StringEntity entity;
        try {
            entity = new StringEntity(json);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
        httpPost.setEntity(entity);
        long start = System.currentTimeMillis();
        try (CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httpPost)) {
            int httpCode = response.getStatusLine().getStatusCode();
            String body = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.printf("httpclient post, url=%s, param=%s, cost=%sms,  httpCode=%s, headers=%s body=%s", url, json, System.currentTimeMillis() - start, httpCode, getHttpHeadersAsPlainText(response.getAllHeaders()), body);
            return body;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    private static String getHttpHeadersAsPlainText(Header[] headers) {
        if (headers == null || headers.length == 0) {
            return "";
        }
        Map<String, List<String>> map = new HashMap<>();
        for (Header header : headers) {
            List<String> stringList = map.getOrDefault(header.getName(), new ArrayList<>());
            map.putIfAbsent(header.getName(), stringList);
            stringList.add(header.getValue());
        }
        StringBuilder sb = new StringBuilder("\n");
        map.entrySet().forEach(e -> sb.append(e.getKey()).append(": ").append(getAsString(e.getValue())).append('\n'));
        return sb.toString();
    }

    private static String getAsString(List<String> stringList) {
        if (stringList == null || stringList.isEmpty()) {
            return "";
        }
        StringBuilder sb = new StringBuilder();
        stringList.forEach(str -> sb.append(str).append("; "));
        return sb.substring(0, sb.length() - 2);
    }
}
